package  
{
	import fl.controls.TextArea;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.events.ServerSocketConnectEvent;
	import flash.net.ServerSocket;
	import flash.net.Socket;
	
	/**
	 * 
	 * @author Metal Slime
	 */
	public class RemoteControllerServer extends MovieClip 
	{
		private var _server:ServerSocket;
		private var _port:int = 8000;
		private var _host:String = "192.168.1.100";
		private var _client:Socket;
		private var _ta:TextArea;
		private var _mc:MovieClip;
		private var _tempArr:Array = [];
		
		public function RemoteControllerServer() 
		{
			stage? init() : addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			initVars();
			initState();
			initEvents();
			run();
		}
		
		private function initVars():void 
		{
			_server = new ServerSocket();
			_ta = this.t;
			_mc = this.mc;
		}
		
		/**
		 * 添加文本
		 * @param	...rest
		 */
		private function addText(...rest):void {
			_ta.appendText(rest.join(" ") + "\n");
			_ta.verticalScrollPosition = _ta.textHeight;
		}
		
		private function initState():void 
		{
			
		}
		
		private function initEvents():void 
		{
			_server.addEventListener(Event.CLOSE, onClose);
			_server.addEventListener(ServerSocketConnectEvent.CONNECT, onConnected);
			resetBtn.addEventListener(MouseEvent.CLICK, resetMc);
			//addEventListener(Event.ENTER_FRAME, onFrame);
		}
		
		private function onFrame(e:Event):void 
		{
			if (_tempArr.length > 0) {
				var pos:Array = _tempArr.shift().split(",");
				addText("接收到客户端信息：", "id:" + pos[2], "x:" + pos[0], "y:" + pos[1]);
				_mc.x += Number(pos[0]);
				_mc.y += Number(pos[1]);
			}
		}
		
		private function resetMc(e:MouseEvent):void 
		{
			_mc.x = 500;
			_mc.y = 300;
		}
		
		private function onClose(e:Event):void 
		{
			addText("服务器已关闭");
		}
		
		private function onConnected(e:ServerSocketConnectEvent):void 
		{
			_client = e.socket;
			addText("接收到连接:", _client);
			_client.addEventListener(Event.CLOSE, onClientClose);
			_client.addEventListener(ProgressEvent.SOCKET_DATA, onClientData);
		}
		
		private function onClientData(e:ProgressEvent):void 
		{
			//_tempArr.push(_client.readUTF());
			var pos:Array = _client.readUTF().split(",");
			addText("接收到客户端信息：", "id:" + pos[2], "x:" + pos[0], "y:" + pos[1]);
			_mc.x += Number(pos[0]);
			_mc.y += Number(pos[1]);
			_client.flush();
		}
		
		private function onClientClose(e:Event):void 
		{
			addText("客户端已断开");
		}
		
		private function run():void 
		{
			_server.bind(_port, _host);
			_server.listen();
		}
	}

}